/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.inmp.message;

import java.lang.reflect.Method;

import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.log4j.Logger;

import com.sinodata.bsm.inmp.ProbeEnv;
import com.sinodata.bsm.inmp.service.ServiceFactory;
import com.sinodata.bsm.common.message.BsmActiveMQFactory;
import com.sinodata.bsm.common.message.ServiceMessage;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author tangli
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-6-12 下午3:35:22          tangli         1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class AsynMessageListener implements MessageListener, ExceptionListener {
    private static AsynMessageListener instance = new AsynMessageListener();
    private Session session;
    private Destination destination;
    private String queueName = null;
    private MessageConsumer consumer = null;
    private int ackMode = Session.AUTO_ACKNOWLEDGE;
    private boolean isRunning = false;
    private static final Logger logger = Logger.getLogger(AsynMessageListener.class);

    private AsynMessageListener() {
        try {
            queueName = "ASYN_CTP_" + ProbeEnv.probeId;
            session = BsmActiveMQFactory.getInstance().getSession(false, ackMode);
            destination = session.createQueue(queueName);
            consumer = session.createConsumer(destination);
            clean(consumer);
            consumer.setMessageListener(this);
        } catch (Exception ex) {
            logger.error("error create message queue:" + this.queueName, ex);
        }
    }

    public static AsynMessageListener getInstance() {
        return instance;
    }

    public void start() {
        this.isRunning = true;
    }

    public void stop() {
        this.isRunning = false;
    }

    /**
     * 注意，此队列是异步对列，注动接收消息
     */
    public void onMessage(Message message) {
        try {
            if (!isRunning) {
                return;
            }
            ObjectMessage objmsg = (ObjectMessage) message;
            Object msg = objmsg.getObject(); //待序列化的消息
            if (msg instanceof ServiceMessage) {
                ServiceMessage serviceMessage = (ServiceMessage) msg;
                String serviceId = serviceMessage.getSrvId();
                String methodName = serviceMessage.getMethod();
                Object[] params = serviceMessage.getParams();
                Object service = ServiceFactory.get(serviceId);
                Class[] paramTypes = null;
                if (params != null) {
                    paramTypes = new Class[params.length];
                    for (int i = 0; i < paramTypes.length; i++) {
                        paramTypes[i] = params[i].getClass();
                    }
                }
                Method method;
                method = service.getClass().getDeclaredMethod(methodName, paramTypes);
                method.invoke(service, params);
            }
        } catch (Exception e) {
            logger.error("failed to get method", e);
        }

    }

    private void clean(MessageConsumer consumer) {
        while (true) {
            try {
                if (consumer.receive(1000L) == null) {
                    break;
                }
            } catch (JMSException e) {
                logger.error("清空消息队列失败", e);
                break;
            }
        }
    }

    public synchronized void onException(JMSException ex) {
        logger.error("", ex);
    }

}
